import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.tasks.UnsupportedFormatException;

import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;

/**
 * @description:
 * @author: LuoLong
 * @create: 2018-09-11 09:03
 **/
public class Main {
    public static void main(String[] args) throws IOException {
        /*当前目录*/
        File picDir = new File("./");
        System.out.println("currentPath: " + picDir.getAbsolutePath());
        if (picDir.isDirectory()) {
            File[] picFiles = picDir.listFiles();
            for (File file : picFiles) {
                if (file.isFile()) {
                    try {
                        if (ImageIO.read(file) == null) continue;

                        StringBuilder sb = new StringBuilder("(" + file.getName() + "):");
                        sb.append(Main.showFileLength(file.length()) + "->");
                        Thumbnails.of(file).scale(1).toFile(file);
                        sb.append(Main.showFileLength(file.length()));
                        System.out.println(sb);

                    } catch (UnsupportedFormatException e) {
                        System.err.println("skip file: " + file.getName());
                    } catch (ArrayIndexOutOfBoundsException e) {
                        System.err.println("could not compress the file: " + file.getName());
                    }
                }
            }
        }
    }

    /**
     * 显示文件大小
     * 最大显示单位PB
     */
    public static String showFileLength(double fileLength) {
        String[] a = {"B", "K", "M", "G", "T", "P"};

        int i = 0;
        while (fileLength >= 1024 && i < a.length - 2) {
            i++;
            fileLength /= 1024.0;
        }
        return String.format("%.2f", fileLength) + a[i];
    }

}
